import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";
import { getToken } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  baseURL: "/pet-api", // 全局添加/pet-api前缀
  timeout: 10000, // 请求超时时间
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 获取token
    const token = getToken();
    // 如果有token，将其添加到请求头中
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // 如果状态码不是200，表示请求出错
    if (res.code !== 200) {
      // 显示错误消息
      ElMessage({
        message: res.msg || "网络请求错误",
        type: "error",
        duration: 5000,
      });

      // 处理特定错误，例如401未授权
      if (res.code === 401) {
        // 弹窗提示重新登录
        ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 清除用户数据并重新登录
          localStorage.removeItem("token");
          router.push(`/login?redirect=${router.currentRoute.value.fullPath}`);
        });
      }

      return Promise.reject(new Error(res.msg || "网络请求错误"));
    } else {
      return res;
    }
  },
  (error) => {
    console.error("响应错误:", error);
    ElMessage({
      message: error.message || "网络请求错误",
      type: "error",
      duration: 5000,
    });
    return Promise.reject(error);
  }
);

export default service;
